/*
 * Copyright (c) 2002-2004
 * All rights reserved.
 */
package com.atlassian.jira.plugin.workflow.blockinglinks.condition;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.ManagerFactory;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.link.IssueLink;
import com.opensymphony.module.propertyset.PropertySet;
import com.opensymphony.workflow.Condition;
import com.opensymphony.workflow.spi.WorkflowEntry;
import org.apache.log4j.Category;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;


public class BlockingLinksCondition implements Condition
{
    private static final Category log = Category.getInstance(BlockingLinksCondition.class);


    public boolean passesCondition(Map transientVars, Map args, PropertySet ps)
    {
        // incidencia actual
        Issue issue = (Issue) transientVars.get("issue");
        
        // estados permitidos
        String statuses = (String) args.get("statuses");   
        List validStates = Arrays.asList( statuses.split(","));
        
        // incidencias enlazadas ??
   		List inwardLinks = ComponentManager.getInstance().getIssueLinkManager().getInwardLinks(issue.getLong("id"));
   		
   		for (int i = 0; i < inwardLinks.size(); i++)
		{
   			// seguimos un enlace concreto
			IssueLink link = (IssueLink) inwardLinks.get(i);
//			log.error("issueLinkName: " + link.getIssueLinkType().getName());
			
			// el estado de la otra incidencia
			String issueStatus = ((GenericValue ) link.getSource()).getString("status");
			
			// tiene un estado no permitido?
			for ( int j=0; j<1; j++)			
			{
				if (  ! validStates.contains( issueStatus  ) ) {
					return false;					
				}
			}
		}
        return true;
    }
    
}